package com.game.modular.gameCore.map.service.impl;

import com.game.modular.gameCore.map.domain.CoreCity;
import com.game.modular.gameCore.map.mapper.CoreCityMapper;
import com.game.modular.gameCore.map.service.CoreCityService;
import lombok.extern.slf4j.Slf4j;
import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;


/**
 * 城池信息(CoreCity)表服务实现类
 *
 * @author cxy
 * @since 2024-07-30 20:44:32
 */
@Slf4j
@Service
public class CoreCityServiceImpl extends ServiceImpl<CoreCityMapper, CoreCity> implements CoreCityService {
    Cache<String, Map<Long,CoreCity>> cache = Caffeine.newBuilder().build();

    @PostConstruct
    private void init() {
        CoreCity initSelect = CoreCity.builder().build();
        List<CoreCity> list = this.list(new LambdaQueryWrapper<>(initSelect));
        log.info("开始缓存城池信息数据,数据量为:{}",list.size());
        cache.put(
                "coreCity", 
                list.stream().collect(Collectors.toMap(CoreCity::getId, CoreCity -> CoreCity))
        );
        log.info("城池信息数据缓存完成");
    }

    public List<CoreCity> listCache() {
        Map<Long,CoreCity> values = cache.getIfPresent("coreCity");
        if (Objects.isNull(values)) {
            throw new RuntimeException("城池信息数据为空");
        }
        return new ArrayList<>(values.values());
    }
    public  Map<Long,CoreCity> mapCache() {
        Map<Long,CoreCity> values = cache.getIfPresent("coreCity");
        if (Objects.isNull(values)) {
            throw new RuntimeException("城池信息数据为空");
        }
        return values;
    }
    
    public CoreCity getCache(Long id) {
        Map<Long,CoreCity> values = cache.getIfPresent("coreCity");
        if (Objects.isNull(values)) {
            throw new RuntimeException("城池信息数据为空");
        }
        return values.get(id);
    }
}
